#include <stdio.h>
#include <dirent.h>
#include <e_file.h>
#include <errno.h>
#include <string.h>

#define BUFFSIZE 256L

int parse_dir (const char *path);

int main (int argc, char *argv[])
{
	if (argc < 2) {
		return -1;
	}
	parse_dir (argv[1]);
	return 0;
}


int parse_dir (const char *path)
{
	struct stat s;
	DIR *dp = NULL;
	struct dirent *entry;
	char buf[BUFFSIZE] = {0};

	if (-1 == stat (path, &s))
	{
		perror ("stat()");
		return -1;
	}
	if (!S_ISDIR(s.st_mode)) {
		return -1;
	}
	//打开目录 
	dp = opendir (path);
	if (NULL == dp) {
		perror ("opendir()");
		return -1;
	}
	//读目录
	while (1) {
		entry = readdir (dp);
		if (NULL == entry) {
			if (errno) {
				perror ("readdir()");
				goto ERROR;
			}
			break;
		}
		if (strcmp (".", entry->d_name) == 0 || strcmp("..", entry->d_name) == 0) {
			continue;
		}
		//假定path--> /etc  ---> "/etc/passwd" "/etc/dir" 
		//d_name --> "passwd" "dir" 
		memset (buf, '\0', BUFFSIZE);
		//先将"/etc"放进去
		strncpy (buf, path, BUFFSIZE); 
		//多加/ 是允许的, 防止没有/
		strncat (buf, "/", BUFFSIZE-strlen(path));
		strncat (buf, entry->d_name, BUFFSIZE-strlen(buf));
		printf ("%s\n", buf);
		//文件名 递归解析每一级目录
		parse_dir(buf);
	}

	closedir (dp);
	return 0;
ERROR:
	closedir (dp);
	return -1;
}


